﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 大话西游子线程控制补丁
{
	public partial class Form1 : Form
	{
		private BackgroundWorker _bckWorker_ThreadHdl;
		private ThreadList thread;
		private static int ThreadInterval=500;
		public Form1()
		{
			InitializeComponent();
			thread = new ThreadList();
			_bckWorker_ThreadHdl = new BackgroundWorker() { WorkerReportsProgress=true,WorkerSupportsCancellation=true};
			_bckWorker_ThreadHdl.DoWork += _bckWorker_ThreadHdl_DoWork;
			_bckWorker_ThreadHdl.ProgressChanged += _bckWorker_ThreadHdl_ProgressChanged;
			_bckWorker_ThreadHdl.RunWorkerCompleted += _bckWorker_ThreadHdl_RunWorkerCompleted;
		}

		private void _bckWorker_ThreadHdl_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
		{
			OpShowStatus.Text = "监测已停止";
		}

		private void _bckWorker_ThreadHdl_ProgressChanged(object sender, ProgressChangedEventArgs e)
		{
			if(e.ProgressPercentage==0)
				OpShowStatus.Text = "监测开始";
			else
			{
				object[] info = (object[])e.UserState;
				OpShowStatus.Text = string.Format("完成本轮监测,关闭/合计:{0}/{1}",info[0],info[1]);
			}
				
		}

		private void _bckWorker_ThreadHdl_DoWork(object sender, DoWorkEventArgs e)
		{
			try
			{
				if (sender is BackgroundWorker worker)
				{
					while (!worker.CancellationPending)
					{
						_bckWorker_ThreadHdl.ReportProgress(0);
						System.Threading.Thread.Sleep(100);

						_bckWorker_ThreadHdl.ReportProgress(50, new object[] { thread.Refresh(out int threadHdlNum),threadHdlNum
				});
						System.Threading.Thread.Sleep(ThreadInterval);
					}
					
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message + ex.StackTrace);
			}

		}

		private void Form1_Load(object sender, EventArgs e)
		{

		}

		private void IpThreadCloseStatus_TextChanged(object sender, EventArgs e)
		{
			if (sender is TextBox keyStatus)
			{
				Thread.Chk_Close = keyStatus.Text;
			}
		}

		private void IpThreadCloseTime_TextChanged(object sender, EventArgs e)
		{
			if (sender is TextBox time)
			{
				int interval = Convert.ToInt32(time.Text);
				if (interval > 0)
				{
					Thread.Chk_CloseTime = interval;
				}
			}
		}

		private void textBox1_TextChanged(object sender, EventArgs e)
		{

		}

		private void textBox1_TextChanged_1(object sender, EventArgs e)
		{
			
			if (sender is TextBox time)
			{
				int interval = Convert.ToInt32(time.Text);
				if (interval > 0)
				{
					ThreadInterval = interval;
				}
			}
		}

		private void BtnRun_Click(object sender, EventArgs e)
		{
			if(sender is Button btn)
			{
				switch (btn.Text)
				{
					case "开始":
						btn.Text = "停止";
						_bckWorker_ThreadHdl.RunWorkerAsync();
						break;
					case "停止":
						btn.Text = "开始";
						_bckWorker_ThreadHdl.CancelAsync();
						break;
				} 
			}
		}
	}
}
